// components/audio.js
const audioCtx = wx.createInnerAudioContext();
Component({
  /**
   * 组件的属性列表
   */

  properties: {
    correctList: {
      type: Array,
      value: []
    }
  },

  lifetimes: {
    attached: function () {
      console.log('在组件实例进入页面节点树时执行');
      console.log(this.data.correctList)
      this.stopAllVoice();
    },
    detached: function () {
      console.log('在组件实例被从页面节点树移除时执行');
      console.log(this.data.voiceObj)
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    correctedList: []
  },

  // 数据监听器
  observers: {
    'correctList': function(newD) {
      // 在 numberA 或者 numberB 被设置时，执行这个函数
      console.log(this.data.correctedList);
      this.setData({
        correctedList:newD
      })
      console.log('numberB 被设置时，执行这个函数')
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 暂停所有
    stopAllVoice() {
      var arr = this.data.correctList;
      arr.map(function (item, index, arr) {
        item.hasPlay = false
      })
      this.setData({
        correctedList: arr
      })
    },

    playVoice(e) {
      this.stopAllVoice()
      var that = this
      const index = e.currentTarget.dataset.index;
      let item = that.data.correctedList[index];
      audioCtx.autoplay = false;
      audioCtx.startTime = 0;
      audioCtx.src = item.correctVoiceUrl
      audioCtx.play();
      var hasPlay = 'correctedList[' + index + '].hasPlay'
      that.setData({
        [hasPlay]: true
      })

      audioCtx.onStop(function () {
        var hasPlay = 'correctedList[' + index + '].hasPlay'
        that.setData({
          [hasPlay]: false
        })
      })

      // 监听音频暂停事件
      audioCtx.onPause(function () {
        var hasPlay = 'correctedList[' + index + '].hasPlay'
        that.setData({
          [hasPlay]: false
        })
      })

      audioCtx.onEnded(() => {
        audioCtx.stop()
        var hasPlay = 'correctedList[' + index + '].hasPlay'
        that.setData({
          [hasPlay]: false
        })
      })
    },

    // 暂停播放
    stopVoice(e) {
      var that = this;
      const index = e.currentTarget.dataset.index;
      let item = this.data.correctedList[index];
      audioCtx.pause();
      var hasPlay = 'correctedList[' + index + '].hasPlay'
      that.setData({
        [hasPlay]: false
      })
    },

    // 询问是否确认删除
    delCorrect(e) {
      var index = e.currentTarget.dataset.index;
      var myEventDetail = {index}
      var myEventOption = {}// 触发事件的选项
      this.triggerEvent('ondelCorrect', myEventDetail, myEventOption)
    }
  }
})
